package chances.epg.data.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import chances.epg.data.PageBean;
import chances.epg.entity.content.Album;
import chances.epg.entity.content.AlbumItem;
import chances.epg.entity.content.Category;
import chances.epg.entity.content.CategoryItem;
import chances.epg.entity.content.EpgContent;
import chances.epg.entity.content.Episode;
import chances.epg.entity.content.Information;
import chances.epg.entity.content.Link;
import chances.epg.entity.content.Media;
import chances.epg.entity.content.Program;
import chances.epg.entity.content.ProgramOffering;
import chances.epg.entity.content.Schedule;
import chances.epg.entity.content.Series;
import chances.epg.entity.content.ServiceContent;
import chances.epg.entity.content.SubjectArea;
import chances.epg.entity.content.SubjectPage;


@Service
public class ContentService extends EpgService {
	/**
	 * 
	 * @param itemId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public CategoryItem getCateogryItemById(Long itemId) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("itemId", itemId);
		try{
		    List<CategoryItem> result = (List<CategoryItem>)this.queryForList("getCategoryItemById",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Category getCategoryByCode(String code) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("categoryCode", code);
		try{
		    List<Category> result = (List<Category>)this.queryForList("getCategoryByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Category> getCategoryLists(String parentCode){
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("parentCode", parentCode);
		
		try{
			return (List<Category>)this.queryForList("getCategorysByParentCode", paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param categoryCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CategoryItem> getCategoryItems(Map<String,Object> paramsMap,boolean byParent){
		paramsMap.put("curTime", new Date());
		
		try{
			if(byParent){
				return (List<CategoryItem>)this.queryForList("getCategoryItemsByParent", paramsMap);
			}else{
			    return (List<CategoryItem>)this.queryForList("getCategoryItems", paramsMap);
			} 
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param categoryCode
	 * @param size
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CategoryItem> getCategoryItems(Map<String,Object> paramsMap,int start,int size,boolean byParent){
		paramsMap.put("curTime", new Date());
		try{
			if(byParent){
				 return (List<CategoryItem>)this.queryForList("getCategoryItemsByParent", paramsMap,start,size);
			}else{
			    return (List<CategoryItem>)this.queryForList("getCategoryItems", paramsMap,start,size);
			}
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param categoryCode
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CategoryItem> getCategoryItems(Map<String,Object> paramsMap,int start,PageBean pageBean,boolean byParent){
		paramsMap.put("curTime", new Date());		
		try{
			if(byParent){
				return (List<CategoryItem>)this.queryForList("getCategoryItemsByParent",paramsMap,start,pageBean);
			}else{
			    return (List<CategoryItem>)this.queryForList("getCategoryItems",paramsMap,start,pageBean);
			}
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 根据多个栏目编码查询编排数据.
	 * @param catCodes
	 * @param start
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CategoryItem> getCategoryItemsByCodes(String[] catCodes,int start,PageBean pageBean) {
		if(catCodes == null
				|| catCodes.length <=0){
			return new ArrayList<CategoryItem>();
		}
		
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		String param  = "'" + catCodes[0] + "'";
		
		for (int i = 1; i < catCodes.length; i++) {
			param  += ",";
			param  += "'" + catCodes[i] + "'";
		}
		
		paramsMap.put("codes", param);
		paramsMap.put("curTime", now);
		
		try{
		    return (List<CategoryItem>)this.queryForList("getCategoryItemsByCodes",paramsMap,start,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 查询专栏中内容列表.
	 * @param albumCode
	 * @param size
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<AlbumItem> getAlbumItems(String albumCode,int start,int size) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("albumCode", albumCode);
		paramsMap.put("curTime",new Date());
		
		try{
		    return (List<AlbumItem>)this.queryForList("queryAlbumItemByAlbumCode", paramsMap,start,size);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 查询专栏中内容列表.
	 * @param albumCode
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<AlbumItem> getAlbumItems(String albumCode,int start,PageBean pageBean) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("albumCode", albumCode);
		paramsMap.put("curTime",new Date());
		
		try{
		    return (List<AlbumItem>)this.queryForList("queryAlbumItemByAlbumCode", paramsMap,start,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Program> getProgramsOfAlbum(String albumCode,int start,PageBean pageBean) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("albumCode", albumCode);
		paramsMap.put("curTime",new Date());
		
		try{
		    return (List<Program>)this.queryForList("queryProgramsOfAlbum", paramsMap,start,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param seriesCode
	 * @param size
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Episode> getEpisodes(String seriesCode) {
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("seriesCode", seriesCode);
		paramsMap.put("curTime", now);
		
		try{
		    return (List<Episode>)this.queryForList("queryEpisodeBySeriesCode",paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param seriesCode
	 * @param size
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Episode> getEpisodes(String seriesCode,String seriesType) {
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("seriesCode", seriesCode);
		paramsMap.put("curTime", now);
		paramsMap.put("seriesType", seriesType);
		
		try{
		    return (List<Episode>)this.queryForList("queryEpisodeBySeriesCode",paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 根据剧集索引获取下一集剧集.
	 * @param seriesCode
	 * @param episodeIndex
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Episode getNextEpisode(String seriesCode,int episodeIndex){
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("seriesCode", seriesCode);
		paramsMap.put("episodeIndex", episodeIndex);
		paramsMap.put("curTime", now);
		
		try{
			List<Episode> result =  (List<Episode>)this.queryForList("queryNextEpisode",paramsMap,0,1);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param seriesCode
	 * @param size
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Episode> getEpisodes(String seriesCode,int start,int size) {
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("seriesCode", seriesCode);
		paramsMap.put("curTime", now);
		
		try{
		    return (List<Episode>)this.queryForList("queryEpisodeBySeriesCode", paramsMap, start,size);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
		
	}
	
	/**
	 * 
	 * @param seriesCode
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Episode> getEpisodes(String seriesCode,PageBean pageBean) {
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("seriesCode", seriesCode);
		paramsMap.put("curTime", now);
		
		try{
		    return (List<Episode>)this.queryForList("queryEpisodeBySeriesCode", paramsMap, 0,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Episode> getEpisodes(String seriesCode,String seriesType,PageBean pageBean) {
		Date now = new Date();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("seriesCode", seriesCode);
		paramsMap.put("curTime", now);
		paramsMap.put("seriesType", seriesType);
		
		try{
		    return (List<Episode>)this.queryForList("queryEpisodeBySeriesCode", paramsMap, 0,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	
	/**
	 * 获取专辑的默认首页.
	 * @param subjectCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public SubjectPage getDefaultPageOfSubject(String subjectCode) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("subjectCode", subjectCode);
		
		try{
			List<SubjectPage> result =  (List<SubjectPage>)this.queryForList("querySubjectPageOfSubject", paramsMap);
			
			for (SubjectPage subjectPage : result) {
			    if(subjectPage.isDefaultFlag()){
			    	return subjectPage;
			    }
			}
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 根据专题页面编码查询专题页面.
	 * @param subjectPageCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public SubjectPage getSubjectPageByCode(String subjectPageCode) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("pageCode", subjectPageCode);
		try{
		    List<SubjectPage> result = (List<SubjectPage>)this.queryForList("querySubjectPageByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取专辑页面中热点信息.
	 * @param subjectPageCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<SubjectArea> getSubjectAreas(String subjectPageCode) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("pageCode", subjectPageCode);
		try{
		    return (List<SubjectArea>)this.queryForList("querySubjectAreaOfPage", paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取连续剧剧头信息.
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Series getSeriesByCode(String code) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("contentCode", code);
		try{
		    List<Series> result = (List<Series>)this.queryForList("querySeriesByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取专栏信息.
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Album getAlbumByCode(String code) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("contentCode", code);
		try{
		    List<Album> result = (List<Album>)this.queryForList("queryAlbumByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
	    }finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取单剧集内容信息.
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Program getProrgamByCode(String code) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("contentCode", code);
		
		try{
		    List<Program> result = (List<Program>)this.queryForList("queryProgramByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取Offering信息
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<ProgramOffering> getProgramOfferingOfProgram(String code) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("contentCode", code);
		
		try{
		    return (List<ProgramOffering>)this.queryForList("queryOfferingByProgramCode", paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取Offering信息
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Media> getMediaOfProgram(String code) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("mediaType", "movie");
		paramsMap.put("contentCode", code);
		
		try{
		    return (List<Media>)this.queryForList("queryMediaByContentCode", paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 获取Offering信息
	 * @param code
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Media getMediaById(Long id) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("mediaId", id);
		
		try{
			List<Media> result = (List<Media>)this.queryForList("queryMediaById", paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param offeringId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public ProgramOffering getProgramOfferingByOfferingId(String offeringId){
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("offeringId", offeringId);
		try{
			List<ProgramOffering> result = (List<ProgramOffering>)this.queryForList("queryOfferingByOfferingId", paramsMap);
			return result.size() > 0 ? result.get(0) : null;
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param categoryCode
	 * @param start
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Category> getCategoryLists(String parentCode,int start,PageBean pageBean){
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("parentCode", parentCode);
		
		try{
			return (List<Category>)this.queryForList("getCategorysByParentCode",paramsMap,start,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param parentCode
	 * @param start
	 * @param size
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Category> getCategoryLists(String parentCode,int start,int size){
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("parentCode", parentCode);
		
		try{
			return (List<Category>)this.queryForList("getCategorysByParentCode", paramsMap,start,size);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}
	
	/**
	 * 
	 * @param categoryCode
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CategoryItem> getCategoryItemContent(String categoryCode,int start,PageBean pageBean){
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("categoryCode", categoryCode);
		paramsMap.put("curTime", new Date());
		
		try{
			return (List<CategoryItem>)this.queryForList("getCategoryItemContentByCodes",paramsMap,start,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}

    /**
     * @param programCode
     * @return
     */
    @SuppressWarnings("rawtypes")
	public Media getEpgMovieByContentCode(String contentCode) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("mediaType", "movie");
        paramsMap.put("contentCode", contentCode);
        try {
            List list = this.queryForList("queryMediaByContentCode", paramsMap);
            if (list.size() > 0) {
                return (Media) list.get(0);
            } else {
                return null;
            }
        } finally {
            paramsMap.clear();
            paramsMap = null;
        }
    }
    
    /**
     * 根据编码查询图文.
     * @param contentCode
     * @return
     */
    @SuppressWarnings("unchecked")
	public Information getInformationByCode(String contentCode) {
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("contentCode", contentCode);
        try{
            List<Information> result = (List<Information>)this.queryForList("queryInformationByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
        }finally{
            paramsMap.clear();
            paramsMap = null;
        }
    }   
    
    /**
     * 根据编码查询外部链接.
     * @param contentCode
     * @return
     */
    @SuppressWarnings("unchecked")
	public Link getLinkByCode(String contentCode) {
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("contentCode", contentCode);
        try{
            List<Link> result = (List<Link>)this.queryForList("queryLinkByCode",paramsMap);
			return result.size() > 0 ? result.get(0) : null;
        }finally{
            paramsMap.clear();
            paramsMap = null;
        }
    }
    
    /**
     * 查询所有内容.
     * @param pageBean
     * @return
     */
    @SuppressWarnings("unchecked")
	public List<EpgContent> getAllEpgContents(PageBean pageBean) {
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
		try{
		    return (List<EpgContent>)this.queryForList("queryAllContent",paramsMap,0,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
    }
    
    /**
     * 获取节目单
     * @param schedulCode
     * @return
     */
    public Schedule getScheduleByCode(String scheduleCode){
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	paramsMap.put("code", scheduleCode);
		try{
		    return (Schedule)this.queryForObject("getScheduleByCode", paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
    }
 
    /**
     * 按名称首字符检索
     * @param initals
     * @return
     */
    @SuppressWarnings("unchecked")
	public List<EpgContent> searchContentByInitals(String initals,String baseTypeCode, String tagString,PageBean pageBean){
    	if(StringUtils.isBlank(initals)){
    		return new ArrayList<EpgContent>();
    	}
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	paramsMap.put("searchName", "%" + initals.toLowerCase() + "%");
    	
    	String[] types = StringUtils.split(tagString, ",");
    	List<String> typeArray = null;
    	if(types.length > 0){
    		typeArray = new ArrayList<String>();
    		for(String temp : types){
    			typeArray.add(temp);
    		}
    	}
    	paramsMap.put("tagString", typeArray);
    	if(StringUtils.isNotBlank(baseTypeCode)){
    		paramsMap.put("baseType", baseTypeCode);
    	}
		try{
			return (List<EpgContent>)this.queryForList("queryContentBySearchName",paramsMap,0,pageBean);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
    }
    
    /**
     * 按名称首字符，标签检索
     * @param initals
     * @param tags
     * @return
     */
	@SuppressWarnings("unchecked")
	public List<EpgContent> searchContentByInitalsAndTags(String initals, String tags, PageBean pageBean) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("initals", "%" + initals.toLowerCase() + "%");
		paramsMap.put("tags", tags.toLowerCase());
		try {
			return (List<EpgContent>) this.queryForList("queryProgramByInitalsAndMainFolder", paramsMap, 0, pageBean);
		} finally {
			paramsMap.clear();
			paramsMap = null;
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> searchInitalsGroup(String initals, String type) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("initals", "%" + initals.toLowerCase() + "%");
		try {
			if(type.equals(EpgContent.SEARCH_GROUP)) {
				return (List<Map<String, String>>) this.queryForList("queryProgramByInitalsAndMainFolderGroup", paramsMap);
			} else {
				Integer count = (Integer) this.queryForObject("queryProgramByInitalsAndMainFolderAll", paramsMap);
				List<Map<String, String>> result = new ArrayList<Map<String, String>>();
				Map<String, String> val = new HashMap<String, String>();
				val.put("count", count+"");
				result.add(val);
				return result;
			}
		} finally {
			paramsMap.clear();
			paramsMap = null;
		}
		
	}
    
    @SuppressWarnings("unchecked")
	public List<ServiceContent> getServiceByContent(String contentCode) {
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	paramsMap.put("contentCode", contentCode);
    	
		try{
		    return (List<ServiceContent>)this.queryForList("getServiceByContent",paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
    }
    
	public List<CategoryItem> listCateoryContent(List<CategoryItem> items) throws IOException {
		List<String> codes = items.stream().map(s -> {
			return s.getItemCode();
		}).collect(Collectors.toList());
		String[] params = codes.toArray(new String[codes.size()]);
		if (params.length > 0) {
			List<EpgContent> epgContent = this.findContentInCodes(params);
			Map<String, EpgContent> codeMap = epgContent.stream()
					.collect(Collectors.toMap(content -> content.getContentCode(), content -> content));
			items.forEach(s -> {
				s.setSource(codeMap.get(s.getItemCode()));
			});
		}
		return items;

	}

    
    
    @SuppressWarnings("unchecked")
	public List<EpgContent> findContentInCodes( String[] codes) {
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	paramsMap.put("codes", codes);
		try{
		    return (List<EpgContent>)this.queryForList("queryContentInCodes",paramsMap);
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
    }
    
}
